package web

import (
	"fmt"
	"gitee.com/lv_baobao/gcore"
	"gitee.com/lv_baobao/gcore/helper"
	"gitee.com/lv_baobao/gcore/logHelper"
	"gitee.com/lv_baobao/gcore/middlewares"
	"github.com/gin-gonic/gin"
	"github.com/kardianos/service"
	"os"
	"runtime"
	"strings"
	"time"
)

type Config struct {
	ServiceName string
	DisplayName string
	Description string
}

type WebEngine struct {
	Engine *gin.Engine
	Config Config
}

var webEngine *WebEngine

func initLogger() {
	logHelper.InitAppLogger()
}

func NewWebEngine(config Config) *WebEngine {
	initLogger()
	webEngine = &WebEngine{}
	webEngine.Config = config
	e := gin.New()
	e.Use(middlewares.Cors())
	logHelper.Info("配置跨域中间件成功")
	// swagger访问地址 http://localhost:8080/swagger/index.html
	e.Use(middlewares.ExceptionMiddleware())
	redisConfig := gcore.NewAppSettingsHelper().GetAppConfig().Redis
	logHelper.Info("redis server type is ", redisConfig.ServerType)
	logHelper.Info("配置异常中间件成功")
	webEngine.Engine = e
	return webEngine
}

func (e *WebEngine) Any(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.Any(relativePath, handlers...)
}

func (e *WebEngine) GET(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.GET(relativePath, handlers...)
}

func (e *WebEngine) POST(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.POST(relativePath, handlers...)
}

func (e *WebEngine) PUT(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.PUT(relativePath, handlers...)
}

func (e *WebEngine) DELETE(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.DELETE(relativePath, handlers...)
}

func (e *WebEngine) OPTIONS(relativePath string, handlers ...gin.HandlerFunc) {
	e.Engine.OPTIONS(relativePath, handlers...)
}

func (e *WebEngine) LoadHTMLGlob(pattern string) {
	e.Engine.LoadHTMLGlob(pattern)
}

func (e *WebEngine) Use(middleware ...gin.HandlerFunc) {
	e.Engine.Use(middleware...)
}

func (e *WebEngine) Run2() {
	prg := &program{}
	environ := runtime.GOOS
	logHelper.Info(environ, "环境运行服务")
	if strings.Index(environ, "window") == -1 {
		prg.run()
		return
	}
	svcConfig := &service.Config{
		Name:        webEngine.Config.ServiceName,
		DisplayName: webEngine.Config.DisplayName,
		Description: webEngine.Config.Description,
	}

	s, err := service.New(prg, svcConfig)
	if err != nil {
		logHelper.Error(err)
	}

	if err != nil {
		logHelper.Error(err)
	}

	if len(os.Args) > 1 {
		if os.Args[1] == "install" {
			err := s.Install()
			if err != nil {
				logHelper.Error("服务安装失败", err)
				return
			}
			logHelper.Info("服务安装成功")
			err = s.Start()
			if err != nil {
				logHelper.Error("服务启动失败", err)
				return
			}
			return
		}

		if os.Args[1] == "remove" {
			err := s.Uninstall()
			if err != nil {
				logHelper.Error("服务卸载失败", err)
				return
			}
			logHelper.Info("服务卸载成功")
			return
		}
	}
	err = s.Run()
	if err != nil {
		logHelper.Error(err)
	}
}

func (e *WebEngine) Run() {
	config := gcore.NewAppSettingsHelper().GetAppConfig()
	if config == nil {
		logHelper.Error("未找到配置文件")
		time.Sleep(time.Second * 2)
		return
	}
	if config.AuthCode == "" {
		logHelper.Error("授权码错误，不能使用该服务")
		time.Sleep(time.Second * 2)
		return
	}
	macAddress, _ := helper.GetFirstMacAddress()
	decryptMacAddress := helper.AESCbcDecrypt(helper.AuthKey, config.AuthCode)
	if macAddress != decryptMacAddress {
		if config.AuthCode != "zgrh" {
			logHelper.Error("授权码错误，不能使用该服务")
			time.Sleep(time.Second * 2)
			return
		}
	}

	fmt.Printf("Listening and serving HTTP on %d\n", config.GlobalConfig.ServerPort)
	err := webEngine.Engine.Run(fmt.Sprintf(":%d", config.GlobalConfig.ServerPort))
	if err != nil {
		logHelper.Error("webEngine启动失败", err)
	}
}

type program struct{}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

func (p *program) run() {
	config := gcore.NewAppSettingsHelper().GetAppConfig()
	if config != nil {
		err := webEngine.Engine.Run(fmt.Sprintf(":%d", config.GlobalConfig.ServerPort))
		if err != nil {
			logHelper.Error("webEngine启动失败", err)
		}
	} else {
		logHelper.Error("未找到配置文件")
	}
	time.Sleep(time.Second * 10)
}

func (p *program) Stop(s service.Service) error {
	defer logHelper.Close()
	return nil
}
